﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;

namespace Server
{
    public class JsonSerializer<T> : Object
    {
        /// <summary>
        /// 序列化
        /// </summary>
        public static string GetObjectJsonTo(T t)
        {
            DataContractJsonSerializer json = new DataContractJsonSerializer(t.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, t);
                return Encoding.UTF8.GetString(stream.ToArray());
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        public static T GetJsonToObject(string json)
        {
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                return (T)serializer.ReadObject(ms);
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        public static T GetJsonToObject(Byte[] byteArray)
        {
            string str = Encoding.UTF8.GetString(byteArray);

            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(str.Replace("\0", ""))))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                return (T)serializer.ReadObject(ms);
            }
        }
    }
}
